package com.xchen.imweb.message;

import javax.websocket.Session;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;


public class WebSocketSession {

    private static Map<String, Session> sessionMap = new ConcurrentHashMap<>();
    private static AtomicInteger onlineNum = new AtomicInteger();

    public static int getOnlineUserNum() {
        return onlineNum.get();
    }

    public static boolean isUsernameExist(String username) {
        return sessionMap.containsKey(username);
    }

    public static boolean register(String username, Session session) {
        if (!sessionMap.containsKey(username)) {
            sessionMap.put(username, session);
            onlineNum.incrementAndGet();
            return true;
        }
        return false;
    }

    public static void remove(String username) {
        sessionMap.remove(username);
        onlineNum.decrementAndGet();
    }

    public static Session getSession(String username) {
        return sessionMap.get(username);
    }

    public static List<Session> getSessionList() {
        return new ArrayList<>(sessionMap.values());
    }

}
